<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="88px"
    >
      <el-form-item label="农场编号" prop="farmNo">
        <el-input
          v-model="queryParams.farmNo"
          placeholder="请输入农场编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="农场名称" prop="farmName">
        <el-input
          v-model="queryParams.farmName"
          placeholder="请输入农场名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="农场分类" prop="categoryId">
        <el-input
          v-model="selectedCategoryName"
          placeholder="请选择农场分类"
          clearable
          readonly
          @clear="handleClearCategory"
          class="!w-240px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openCategoryDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['farm:info:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['farm:info:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['farm:info:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="农场编号" align="center" prop="farmNo" fixed="left" width="150px" />
      <el-table-column label="农场名称" align="center" prop="farmName" width="180px" />
      <el-table-column label="农场分类" align="center" prop="categoryName" width="100px" />
      <el-table-column label="农场分类编码" align="center" prop="categoryCode" width="120px" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区县" align="center" prop="district" />
      <el-table-column label="详细门牌号地址" align="center" prop="detailAddress" width="150px" />
      <el-table-column label="经度" align="center" prop="longitude" width="100px" />
      <el-table-column label="纬度" align="center" prop="latitude" width="100px" />
      <el-table-column label="负责人姓名" align="center" prop="managerName" width="120px" />
      <el-table-column label="负责人联系方式" align="center" prop="managerPhone" width="150px" />
      <el-table-column label="负责人身份证号" align="center" prop="managerIdCard" width="150px" />
      <el-table-column label="农场面积（亩）" align="center" prop="farmArea" width="130px" />
      <el-table-column label="农场资质文件" align="center" width="120px">
        <template #default="scope">
          <el-button
            v-if="scope.row.qualificationFiles"
            link
            type="primary"
            @click="handleViewFiles(scope.row.qualificationFiles)"
          >
            查看文件
          </el-button>
          <span v-else class="text-gray-400">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="农场背景简介" align="center" width="120px">
        <template #default="scope">
          <el-button
            v-if="scope.row.backgroundIntro"
            link
            type="primary"
            @click="handleViewIntro(scope.row.backgroundIntro)"
          >
            查看背景
          </el-button>
          <span v-else class="text-gray-400">未填写</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" align="center" prop="loginName" width="120px" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FARM_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="审核状态" align="center" prop="auditStatus" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.AUDIT_STATUS" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="auditRemark" width="120px" />
      <el-table-column
        label="审核时间"
        align="center"
        prop="auditTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="审核人" align="center" prop="auditUser" width="120px" /> -->
      <el-table-column label="备注" align="center" prop="remark" width="120px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" fixed="right" min-width="240px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('view', scope.row.id)"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['farm:info:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="openViolationForm(scope.row)"
            v-hasPermi="['farm:violation-record:create']"
          >
            违规
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['farm:info:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InfoForm ref="formRef" @success="getList" />

  <!-- 违规记录弹窗 -->
  <ViolationRecordForm ref="violationFormRef" @success="handleViolationSuccess" />

  <!-- 分类选择弹窗 -->
  <CategorySelectDialog ref="categoryDialogRef" @confirm="handleCategoryConfirm" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InfoApi, InfoVO } from '@/api/farm/info'
import InfoForm from './InfoForm.vue'
import ViolationRecordForm from './ViolationRecordForm.vue'
import CategorySelectDialog from './CategorySelectDialog.vue'
import type { CategoryVO } from '@/api/farm/category'
import { ElMessageBox } from 'element-plus'

/** 农场信息 列表 */
defineOptions({ name: 'Info' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<InfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  farmNo: undefined,
  farmName: undefined,
  categoryId: undefined as number | undefined,
  categoryCode: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const categoryDialogRef = ref() // 分类选择弹窗
const selectedCategoryName = ref('') // 选中的分类名称
const violationFormRef = ref() // 违规记录弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InfoApi.getInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedCategoryName.value = '' // 清空分类名称
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InfoApi.deleteInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除农场信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 批量删除：逐个调用删除接口
    await Promise.all(checkedIds.value.map((id) => InfoApi.deleteInfo(id)))
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: InfoVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InfoApi.exportInfo(queryParams)
    download.excel(data, '农场信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开分类选择弹窗 */
const openCategoryDialog = () => {
  categoryDialogRef.value?.open()
}

/** 分类选择确认 */
const handleCategoryConfirm = (category: CategoryVO) => {
  queryParams.categoryId = category.id
  selectedCategoryName.value = category.categoryName
}

/** 清空分类选择 */
const handleClearCategory = () => {
  queryParams.categoryId = undefined
  selectedCategoryName.value = ''
}

/** 查看资质文件 */
const handleViewFiles = (files: string) => {
  if (!files) return

  // 文件URL可能是逗号分隔的多个文件
  const fileUrls = files.split(',').filter(Boolean)

  // 如果只有一个文件，直接在新窗口打开
  if (fileUrls.length === 1) {
    window.open(fileUrls[0], '_blank')
    return
  }

  // 如果有多个文件，显示文件列表
  const fileLinks = fileUrls
    .map((url, index) => {
      const fileName = url.substring(url.lastIndexOf('/') + 1)
      return `<div style="margin: 10px 0;">
        <a href="${url}" target="_blank" style="color: #409eff; text-decoration: none;">
          ${index + 1}. ${fileName}
        </a>
      </div>`
    })
    .join('')

  ElMessageBox.alert(
    `<div style="max-height: 400px; overflow-y: auto;">
      <h4 style="margin-bottom: 10px;">农场资质文件列表（共${fileUrls.length}个）：</h4>
      ${fileLinks}
    </div>`,
    '农场资质文件',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

/** 查看农场背景简介 */
const handleViewIntro = (intro: string) => {
  if (!intro) return

  ElMessageBox.alert(
    `<div style="max-height: 500px; overflow-y: auto; padding: 10px; line-height: 1.6;">
      ${intro}
    </div>`,
    '农场背景简介',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customStyle: {
        width: '800px'
      }
    }
  )
}

/** 打开违规记录弹窗 */
const openViolationForm = (row: InfoVO) => {
  violationFormRef.value?.open(row.id, row.farmName, row.farmNo)
}

/** 违规记录添加成功回调 */
const handleViolationSuccess = () => {
  message.success('违规记录添加成功')
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
